package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class RSSController extends HttpServlet {

	@EJB
	private UserDaoLocal userDao;
	
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("RSSController.doGet()");
		
		String userIdString = request.getParameter("id");
		Integer userId = Integer.parseInt(userIdString);

		User user = userDao.findById(userId);
		
		List<Album> albums = albumDao.findAllAlbumsFromUser(userId);
		
		List<Photo> photos = new ArrayList<>();
		for(Album album : albums) {
			photos.addAll(photoDao.findPhotosByAlbumId(album.getId()));
		}
		
		request.setAttribute("photosRss", photos);
		
		Integer port = request.getServerPort();
		String name = request.getServerName();
		String path = request.getContextPath();

		request.setAttribute("port", port);
		request.setAttribute("name", name);
		request.setAttribute("path", path);
		request.setAttribute("user", user);
		
		response.setContentType("application/rss+xml");
		getServletContext().getRequestDispatcher("/rss.jsp").forward(request, response);
		return;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
